package com.aliyun.messagemgt.service;


import com.aliyun.messagemgt.common.dto.send.PushChannelInfo;
import com.aliyun.messagemgt.pojo.vo.MailSendInfoVO;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.internet.MimeMessage;
import java.io.File;

/**
 * @author byp
 * @date 2020/5/18
 */
@Service
public class MailServiceImpl implements MailService {

    @Autowired
    private JavaMailSender javaMailSender;

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public boolean sendAttachmentsMail(PushChannelInfo pushChannelInfo, MailSendInfoVO mailSendInfoVO) {
        MimeMessage message = javaMailSender.createMimeMessage();

        try {
            //是否发送的邮件是富文本（附件，图片，html等） true
            MimeMessageHelper helper = new MimeMessageHelper(message, true);
            helper.setFrom(mailSendInfoVO.getFromUser());
            helper.setTo(mailSendInfoVO.getToUser());
            helper.setSubject(mailSendInfoVO.getSubject());
            helper.setText(mailSendInfoVO.getContent(), true);

            String mailFiles = mailSendInfoVO.getAttachmentAddress();
            if (StringUtils.isNotBlank(mailFiles)) {
                FileSystemResource file = new FileSystemResource(new File(mailFiles));
                String fileName = mailFiles.substring(mailFiles.lastIndexOf(File.separator));
                helper.addAttachment(fileName, file);
            }

            String mailHost = pushChannelInfo.getMailHost();
            String sendName = pushChannelInfo.getSendName();
            String passWord = pushChannelInfo.getPassWord();
            Integer mailPort = pushChannelInfo.getMailPort();
            if(StringUtils.isNotEmpty(mailHost) && StringUtils.isNotEmpty(sendName)
                    && StringUtils.isNotEmpty(passWord) && null != mailPort){
                helper.setFrom(sendName);
                ((JavaMailSenderImpl) javaMailSender).setHost(mailHost);
                ((JavaMailSenderImpl) javaMailSender).setUsername(sendName);
                ((JavaMailSenderImpl) javaMailSender).setPassword(passWord);
                ((JavaMailSenderImpl) javaMailSender).getJavaMailProperties().setProperty("mail.smtp.port", mailPort.toString());
            }


            javaMailSender.send(message);
            //日志信息
            logger.info("邮件已经发送");
            return true;

        } catch (Exception e) {
            logger.error("发送邮件时发生异常!异常信息:{}", e);
            return false;
        }
    }
}
